package com.vvvtimes.demo.controller;

import com.vvvtimes.demo.common.dto.RestResponse;
import com.vvvtimes.demo.domain.dto.EncoderDTO;
import com.vvvtimes.demo.service.EncoderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/encoder")
public class EncoderController {

    @Autowired
    private EncoderService encoderService;

    @RequestMapping(value = "/base64Encoder", method = {RequestMethod.POST, RequestMethod.GET})
    public RestResponse<String> base64Encoder(@RequestBody EncoderDTO encoderDTO) {
        return encoderService.base64Encoder(encoderDTO);
    }

    @RequestMapping(value = "/urlEncoder", method = {RequestMethod.POST, RequestMethod.GET})
    public RestResponse<String> urlEncoder(@RequestBody EncoderDTO encoderDTO) {
        return encoderService.urlEncoder(encoderDTO);
    }


    @RequestMapping(value = "/qrEncoder", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<InputStreamResource> qrEncoder(@RequestBody EncoderDTO encoderDTO) {
        byte[] result = encoderService.qrEncoder(encoderDTO);
        long currentTimeMillis = System.currentTimeMillis();
        String imageName = currentTimeMillis + ".png";

        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", imageName));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(result.length)
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(new ByteArrayInputStream(result)));
    }

}

